
package com.eltonkent.ui;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.eltonkent.R;
import com.eltonkent.db.CredentialTable;
import com.eltonkent.ui.tasks.BackupTask;
import com.eltonkent.ui.tasks.RestoreTask;
import com.eltonkent.util.SDCardInfo;

public final class SettingsActivity extends ParentActivity implements ProgressListener
{

	private RelativeLayout accessbilityPanel;
	// private RelativeLayout localePanel;
	private RelativeLayout dmPanel;
	private TextView accessbilityTextSizePreview;
	private TextView accessbilityTextSize;
	private SeekBar textSizeSlider;
	private static final int DIALOG_BACKUP_CONSENT = 10;

	private static final int DIALOG_BACKUP_PROGRESS = 20;
	private static final int DIALOG_RESTORE_CONSENT = 30;
	private static final int DIALOG_RESTORE_PROGRESS = 40;
	private static final int DIALOG_GET_PASSWORD = 60;
	private Dialog progressDialog;
	private static final int REFRESH_DM_PANEL = 50;

	private Handler handler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESH_DM_PANEL)
			{
				doDataManagementOps();
			}
		}
	};

	@Override
	protected final Dialog onCreateDialog(int id)
	{
		switch(id)
		{
			case DIALOG_BACKUP_CONSENT:
				return getConsentDialog(false);
			case DIALOG_BACKUP_PROGRESS:
				return getProgressDialog(false);
			case DIALOG_RESTORE_CONSENT:
				return getConsentDialog(true);
			case DIALOG_RESTORE_PROGRESS:
				return getProgressDialog(true);
			case DIALOG_GET_PASSWORD:
				return getPasswordDialog();
			default:
				return super.onCreateDialog(id);
		}
	}

	private Dialog getPasswordDialog()
	{
		final Dialog passwordDialog = getCustomDialog(R.layout.dialog_removepassword, R.string.bu_password);
		final EditText password = (EditText) passwordDialog.findViewById(R.id.password);
		final TextView errorText = (TextView) passwordDialog.findViewById(R.id.error_Text);
		TextView dialogTitle = (TextView) passwordDialog.findViewById(R.id.dlg_pass_title);
		dialogTitle.setText(R.string.bu_password_title);
		Button[] okCancel = getOKCancelButtons(passwordDialog);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		btnok.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				String encPassword = null;

				try
				{
					FileInputStream fis = new FileInputStream(ApplicationConstants.BACK_UP_PATH
							+ ApplicationConstants.BACK_UP_FILENAME);
					DataInputStream dis = new DataInputStream(fis);
					byte[] enc = new byte[dis.readInt()];
					fis.read(enc);
					dis.close();
					fis.close();
					CredentialTable table = new CredentialTable(getApplicationContext());
					encPassword = table.getPassword(enc);
				} catch(FileNotFoundException e)
				{
					e.printStackTrace();
				} catch(IOException e)
				{
					e.printStackTrace();
				}
				String enteredPassword = password.getText().toString();
				if(enteredPassword.equals(encPassword))
				{
					errorText.setVisibility(View.GONE);
					password.setText("");
					passwordDialog.dismiss();
					showDialog(DIALOG_RESTORE_PROGRESS);
				} else
				{
					errorText.setText(R.string.password_inavlid);
					errorText.setVisibility(View.VISIBLE);
				}
			}
		});

		btnCancel.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				passwordDialog.dismiss();
				errorText.setVisibility(View.GONE);
				password.setText("");
			}
		});

		return passwordDialog;
	}

	@Override
	protected void onPrepareDialog(int id, final Dialog dialog)
	{
		switch(id)
		{
			case DIALOG_BACKUP_PROGRESS:
				BackupTask task = new BackupTask(getApplicationContext(), this, getApplicationPreferences());
				task.start();
				break;
			case DIALOG_RESTORE_PROGRESS:
				RestoreTask resTask = new RestoreTask(getApplicationContext(), this);
				resTask.start();
		}

	}

	private Dialog getProgressDialog(boolean isRestore)
	{
		progressDialog = getCustomDialog(R.layout.dialog_progress, isRestore ? R.string.setting_restore
				: R.string.setting_bu);
		((TextView) progressDialog.findViewById(R.id.dialogText))
				.setText(isRestore ? R.string.restore_progress : R.string.performing_backup);
		progressDialog.setCancelable(false);
		return progressDialog;
	}

	private Dialog getConsentDialog(final boolean isRestore)
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_deletefolder,
				isRestore ? R.string.setting_restore : R.string.setting_bu);
		TextView tv = (TextView) dialog.findViewById(R.id.dialogText);
		tv.setText(isRestore ? R.string.restore_disclaimer : R.string.backup_disclaimer);
		Button[] okCancel = getOKCancelButtons(dialog);
		Button btnOk = okCancel[0];
		Button btnCancel = okCancel[1];
		btnOk.setText(R.string.yes);
		btnCancel.setText(R.string.no);

		btnCancel.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				dialog.dismiss();
			}
		});

		btnOk.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				dialog.dismiss();
				if(isRestore)
				{
					showDialog(DIALOG_GET_PASSWORD);
				} else
				{
					showDialog(DIALOG_BACKUP_PROGRESS);
				}
			}
		});

		return dialog;
	}

	@Override
	protected void populateUI()
	{
		addToPath(getResources().getString(R.string.settings));
		accessbilityPanel = (RelativeLayout) findViewById(R.id.accessPanel);
		dmPanel = (RelativeLayout) findViewById(R.id.dmPanel);
		// localePanel = (RelativeLayout) findViewById(R.id.localePanel);
		setupSettingsListeners();
		setupWidgets();

	}

	View.OnClickListener accessPanelListener = new View.OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);
			Boolean isClosed = (Boolean) accessbilityPanel.getTag();
			ImageView expButton = (ImageView) findViewById(R.id.access_Expand);
			View accessSettings = findViewById(R.id.settings_AccessPanel);
			if(isClosed == null)
			{
				expButton.setImageResource(R.drawable.btn_collapse);
				accessSettings.setVisibility(View.VISIBLE);
				accessbilityPanel.setTag(new Boolean(false));
			} else
			{
				if(isClosed)
				{
					expButton.setImageResource(R.drawable.btn_collapse);
					accessSettings.setVisibility(View.VISIBLE);
					accessbilityPanel.setTag(new Boolean(false));
				} else
				{
					expButton.setImageResource(R.drawable.btn_expand);
					accessSettings.setVisibility(View.GONE);
					accessbilityPanel.setTag(new Boolean(true));
				}
			}
		}
	};

	// View.OnClickListener localePanelListener = new View.OnClickListener()
	// {
	//
	// @Override
	// public void onClick(View v)
	// {
	// Vibrator vibrator = (Vibrator)
	// getSystemService(Context.VIBRATOR_SERVICE);
	// vibrator.vibrate(50);
	// Boolean isClosed = (Boolean) localePanel.getTag();
	// ImageView expButton = (ImageView) findViewById(R.id.locale_Expand);
	// View accessSettings = findViewById(R.id.settings_LocalePanel);
	// if(isClosed == null)
	// {
	// expButton.setImageResource(R.drawable.btn_collapse);
	// accessSettings.setVisibility(View.VISIBLE);
	// localePanel.setTag(new Boolean(false));
	// } else
	// {
	// if(isClosed)
	// {
	// expButton.setImageResource(R.drawable.btn_collapse);
	// accessSettings.setVisibility(View.VISIBLE);
	// localePanel.setTag(new Boolean(false));
	// } else
	// {
	// expButton.setImageResource(R.drawable.btn_expand);
	// accessSettings.setVisibility(View.GONE);
	// localePanel.setTag(new Boolean(true));
	// }
	// }
	// }
	// };

	View.OnClickListener dmPanelListener = new View.OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);
			Boolean isClosed = (Boolean) dmPanel.getTag();
			ImageView expButton = (ImageView) findViewById(R.id.dm_Expand);
			View accessSettings = findViewById(R.id.settings_DMPanel);
			if(isClosed == null)
			{
				expButton.setImageResource(R.drawable.btn_collapse);
				accessSettings.setVisibility(View.VISIBLE);
				dmPanel.setTag(new Boolean(false));
			} else
			{
				if(isClosed)
				{
					expButton.setImageResource(R.drawable.btn_collapse);
					accessSettings.setVisibility(View.VISIBLE);
					dmPanel.setTag(new Boolean(false));
				} else
				{
					expButton.setImageResource(R.drawable.btn_expand);
					accessSettings.setVisibility(View.GONE);
					dmPanel.setTag(new Boolean(true));
				}
			}
		}
	};
	SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener()
	{

		@Override
		public void onStopTrackingTouch(SeekBar seekBar)
		{
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar)
		{
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
		{
			Log.d("UI", "Seekbar progress ->" + progress);
			accessbilityTextSizePreview.setTextSize(progress);
			accessbilityTextSize.setText(progress + "px");
		}
	};

	View.OnClickListener btnBackupListener = new View.OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			showDialog(DIALOG_BACKUP_CONSENT);
		}
	};

	View.OnClickListener btnRestoreListener = new View.OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			showDialog(DIALOG_RESTORE_CONSENT);
		}
	};

	private void setupSettingsListeners()
	{
		accessbilityPanel.setOnClickListener(accessPanelListener);
		dmPanel.setOnClickListener(dmPanelListener);
		// localePanel.setOnClickListener(localePanelListener);
	}

	private void setupWidgets()
	{
		SharedPreferences prefs = getApplicationPreferences();
		int textSize = prefs.getInt(ApplicationConstants.PREF_TEXT_SIZE,
				ApplicationConstants.PREF_DEF_TEXTSIZE);
		/*--------Accesibility panel setup-------------*/
		accessbilityTextSizePreview = (TextView) findViewById(R.id.textSizePreview);
		accessbilityTextSize = (TextView) findViewById(R.id.textSize);
		textSizeSlider = (SeekBar) findViewById(R.id.textSizeBar);
		textSizeSlider.setOnSeekBarChangeListener(seekBarListener);
		textSizeSlider.setMax(30);
		textSizeSlider.setProgress(textSize);
		accessbilityTextSize.setText(textSize + "px");
		accessbilityTextSizePreview.setTextSize(textSize);

		/*---------------- Applying Text size setting------------- */
		((TextView) findViewById(R.id.settings_access_title)).setTextSize(textSize);
		((TextView) findViewById(R.id.settings_dm_title)).setTextSize(textSize);
		// ((TextView)
		// findViewById(R.id.settings_locale_title)).setTextSize(textSize);
		((TextView) findViewById(R.id.setting_textsize)).setTextSize(textSize);
		accessbilityTextSize.setTextSize(textSize);
		// ((TextView)
		// findViewById(R.id.settings_date_format)).setTextSize(textSize);
		// ((TextView)
		// findViewById(R.id.settings_date_sep)).setTextSize(textSize);
		((TextView) findViewById(R.id.settings_last_backup)).setTextSize(textSize);

		/* Locale Panel */
		// Button dateFormat = (Button) findViewById(R.id.btnDateFormat);
		// dateFormat.setOnClickListener(dateFormatListener);
		// Button dateSep = (Button) findViewById(R.id.btnDateSeparator);
		// dateSep.setOnClickListener(dateSepListener);
		/*---------Data Management Panel----------------*/
		doDataManagementOps();
	}

	// View.OnClickListener dateFormatListener = new View.OnClickListener()
	// {
	// @Override
	// public void onClick(View v)
	// {
	//
	// }
	// };
	//
	// View.OnClickListener dateSepListener = new View.OnClickListener()
	// {
	// @Override
	// public void onClick(View v)
	// {
	//
	// }
	// };

	private void doDataManagementOps()
	{
		/* do dm related text sizing according to prefs */
		SharedPreferences prefs = getApplicationPreferences();
		int textSize = prefs.getInt(ApplicationConstants.PREF_TEXT_SIZE,
				ApplicationConstants.PREF_DEF_TEXTSIZE);
		Button btnRestore = (Button) findViewById(R.id.btnRestore);
		btnRestore.setOnClickListener(btnRestoreListener);
		Button btnBackup = (Button) findViewById(R.id.btnBackup);
		btnBackup.setOnClickListener(btnBackupListener);
		TextView txtBuStatus = ((TextView) findViewById(R.id.settings_bu_status));
		txtBuStatus.setTextSize(textSize);
		TextView txtFileLocation = ((TextView) findViewById(R.id.settings_file_location));
		txtFileLocation.setTextSize(textSize);
		TextView txtFileSize = ((TextView) findViewById(R.id.fileSize));
		txtFileSize.setTextSize(textSize);
		TextView txtFilePath = ((TextView) findViewById(R.id.filePath));
		txtFilePath.setTextSize(textSize);

		if(!SDCardInfo.isMounted())
		{
			/* no sdcard present */
			findViewById(R.id.settings_backup_panel).setVisibility(View.GONE);
			txtBuStatus.setText(R.string.error_nosdcard);
		} else
		{
			File file = new File(ApplicationConstants.BACK_UP_PATH + ApplicationConstants.BACK_UP_FILENAME);
			if(file.exists())
			{
				txtFilePath.setText(file.getPath());
				long size = file.length();
				String sizeText;
				int Mb = 1024 * 1024;
				if(size < Mb)
				{
					float fileSize = size / 1024;
					sizeText = String.valueOf(fileSize) + " kb";
				} else
				{
					sizeText = String.valueOf(size / 2048) + "mb";
				}
				txtFileSize.setText(sizeText);
				txtBuStatus.setText(prefs.getString(ApplicationConstants.PREF_BACKUP_DATE, "n/a"));
				/* toggle visibility */
				btnRestore.setVisibility(View.VISIBLE);
				txtFileSize.setVisibility(View.VISIBLE);
				txtFileLocation.setVisibility(View.VISIBLE);
				txtFilePath.setVisibility(View.VISIBLE);
			} else
			{
				txtFilePath.setVisibility(View.GONE);
				txtFileLocation.setVisibility(View.GONE);
				txtFileSize.setVisibility(View.GONE);
				btnRestore.setVisibility(View.GONE);
			}
		}
	}

	@Override
	protected void setupUI(Bundle savedInstance)
	{
		setContentView(R.layout.activity_settings);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			Log.d("UI", "Back key pressed on folder contents");
			saveSettings();
			removeTextOnlyFromPath(getResources().getString(R.string.settings));
			finish();
			return true;
		}
		return false;
	}

	private void saveSettings()
	{
		SharedPreferences prefs = getApplicationPreferences();
		SharedPreferences.Editor editor = prefs.edit();
		editor.putInt(ApplicationConstants.PREF_TEXT_SIZE, textSizeSlider.getProgress());
		editor.commit();
	}

	@Override
	public void operationCompleted(boolean isRestore)
	{
		((ProgressBar) progressDialog.findViewById(R.id.progress)).setProgress(100);
		if(isRestore)
		{
			dismissDialog(DIALOG_RESTORE_PROGRESS);
		} else
		{
			dismissDialog(DIALOG_BACKUP_PROGRESS);
			Message message = new Message();
			message.what = REFRESH_DM_PANEL;
			handler.sendMessage(message);
		}
	}

	@Override
	public void setProgressStatus(int progress)
	{
		((ProgressBar) progressDialog.findViewById(R.id.progress)).setProgress(progress);

	}
}
